package com.aikon.wht.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author haitao.wang
 */
public class TestOfRecursiceTask extends RecursiveTask<Integer>{

    final int n;

    public TestOfRecursiceTask(int n) {
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (n<=1) {
            return n;
        }
        TestOfRecursiceTask f1 = new TestOfRecursiceTask(n - 1);
        f1.fork();
        TestOfRecursiceTask f2 = new TestOfRecursiceTask(n - 2);
        Integer sum = f2.compute() + f1.join();
        System.out.println(sum);
        return sum;
    }

    public static void main(String[] args) {
        new Thread( () -> {
            ForkJoinPool forkJoinPool = new ForkJoinPool();
            Future<Integer> future = forkJoinPool.submit(new TestOfRecursiceTask(5));
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
